package com.zhiwen.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhiwen.common.api.Result;
import com.zhiwen.common.exception.BusinessException;
import com.zhiwen.domain.entity.Answer;
import com.zhiwen.domain.entity.Comment;
import com.zhiwen.domain.entity.Question;
import com.zhiwen.domain.entity.User;
import com.zhiwen.service.AnswerService;
import com.zhiwen.service.CommentService;
import com.zhiwen.service.QuestionService;
import com.zhiwen.service.SensitiveContentService;
import com.zhiwen.service.UserService;
import com.zhiwen.service.UserAnalyticsService;
import com.zhiwen.service.NotificationProducer;
import com.zhiwen.domain.vo.AnswerVO;
import com.zhiwen.domain.vo.CommentVO;
import com.zhiwen.domain.vo.QuestionVO;
import com.zhiwen.domain.vo.UserVO;
import com.zhiwen.domain.dto.SystemNotificationDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * 管理员控制器
 */
@Tag(name = "管理员功能", description = "管理员相关接口，需要管理员权限")
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
@Slf4j
public class AdminController {

    private final UserService userService;
    private final QuestionService questionService;
    private final AnswerService answerService;
    private final CommentService commentService;
    private final SensitiveContentService sensitiveContentService;
    private final UserAnalyticsService userAnalyticsService;
    private final NotificationProducer notificationProducer;
    // 👇 使用 @Resource 按名称注入
    @Resource(name = "dashboardTaskExecutor") // 指定要注入的 Bean 的名称
    private final Executor dashboardTaskExecutor; // 类型仍然是 Executor


    /**
     * 获取用户列表
     */
    @Operation(summary = "获取用户列表", description = "分页获取所有用户列表，可按关键字搜索，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "current", description = "当前页码", schema = @Schema(defaultValue = "1")),
        @Parameter(name = "size", description = "每页数量", schema = @Schema(defaultValue = "10")),
        @Parameter(name = "keyword", description = "搜索关键词")
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/users")
    @SaCheckRole("ADMIN")
    public Result<Page<UserVO>> getUserList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {

        // 创建分页对象
        Page<User> page = new Page<>(current, size);

        try {
            // 调用Service方法获取用户分页列表
            Page<UserVO> userVOPage = userService.getUserPage(page, keyword);
            return Result.success(userVOPage);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 禁用/启用用户
     */
    @Operation(summary = "更新用户状态", description = "禁用或启用指定用户，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "id", description = "用户ID"),
        @Parameter(name = "status", description = "用户状态：0-禁用，1-启用")
    })
    @ApiResponse(responseCode = "200", description = "更新成功")
    @PutMapping("/users/{id}/status")
    @SaCheckRole("ADMIN")
    public Result<Void> updateUserStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {

        try {
            // 调用Service方法设置用户状态
            if (userService.updateUserStatus(id, status)) {
                return Result.success();
            } else {
                return Result.fail("操作失败");
            }
        } catch (BusinessException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            return Result.fail("系统异常：" + e.getMessage());
        }
    }

    /**
     * 设置用户角色
     */
    @Operation(summary = "设置用户角色", description = "设置指定用户的角色，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "id", description = "用户ID"),
        @Parameter(name = "role", description = "用户角色：1-普通用户，2-专家用户，3-管理员")
    })
    @ApiResponse(responseCode = "200", description = "设置成功")
    @PutMapping("/users/{id}/role")
    @SaCheckRole("ADMIN")
    public Result<Void> updateUserRole(
            @PathVariable Long id,
            @RequestParam Integer role) {

        try {
            // 调用Service方法设置用户角色
            if (userService.updateUserRole(id, role)) {
                return Result.success();
            } else {
                return Result.fail("操作失败");
            }
        } catch (BusinessException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            return Result.fail("系统异常：" + e.getMessage());
        }
    }

    /**
     * 获取待审核问题列表
     */
    @Operation(summary = "获取待审核问题列表", description = "分页获取所有待审核的问题，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "current", description = "当前页码", schema = @Schema(defaultValue = "1")),
        @Parameter(name = "size", description = "每页数量", schema = @Schema(defaultValue = "10"))
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/questions/pending")
    @SaCheckRole("ADMIN")
    public Result<Page<QuestionVO>> getPendingQuestions(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {

        Page<Question> page = new Page<>(current, size);
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();

        // 状态为0表示待审核
        wrapper.eq(Question::getStatus, 0);
        wrapper.orderByDesc(Question::getCreateTime);

        return Result.success(questionService.getQuestionPage(page, wrapper));
    }

    /**
     * 审核问题
     */
    @Operation(summary = "审核问题", description = "审核指定问题，可通过或拒绝，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "id", description = "问题ID"),
        @Parameter(name = "status", description = "审核结果：1-通过，4-拒绝"),
        @Parameter(name = "reason", description = "拒绝理由(拒绝时必填)")
    })
    @ApiResponse(responseCode = "200", description = "审核成功")
    @PutMapping("/questions/{id}/review")
    @SaCheckRole("ADMIN")
    public Result<Void> reviewQuestion(
            @PathVariable Long id,
            @RequestParam Integer status,
            @RequestParam(required = false) String reason) {

        // 审核结果只能为1(通过)或4(拒绝)
        if (status != 1 && status != 4) {
            return Result.fail("无效的审核结果");
        }

        // 如果拒绝，必须提供理由
        if (status == 4 && (reason == null || reason.isEmpty())) {
            return Result.fail("拒绝时必须提供理由");
        }

        try {
            // 查询问题是否存在
            Question question = questionService.getById(id);
            if (question == null) {
                return Result.fail("问题不存在");
            }

            // 只有待审核状态的问题才能审核
            if (question.getStatus() != 0) {
                return Result.fail("该问题已审核");
            }

            // 更新问题状态
            question.setStatus(status);

            // 如果是拒绝，保存理由到备注字段
            if (status == 4) {
                question.setRemark(reason);
            }

            // 设置审核时间
            question.setUpdateTime(LocalDateTime.now());

            // 更新问题
            boolean success = questionService.updateById(question);

            if (success) {
                // 记录审核操作日志
                // 这里可以添加日志记录逻辑

                // 如果采用实时通知，这里可以添加通知用户的逻辑
                // 例如：notificationService.sendNotification(question.getUserId(), "问题审核结果", status == 1 ? "您的问题已通过审核" : "您的问题未通过审核: " + reason);

                return Result.success();
            } else {
                return Result.fail("审核失败，请重试");
            }
        } catch (Exception e) {
            return Result.fail("审核失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户统计数据
     */
    @Operation(summary = "获取用户统计数据", description = "获取平台用户相关的统计数据，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/statistics/users")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> getUserStatistics() {
        try {
            Map<String, Object> statistics = userService.getUserStatistics();
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.fail("获取用户统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除用户
     */
    @Operation(summary = "批量删除用户", description = "批量删除指定用户，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "操作成功")
    @DeleteMapping("/users/batch")
    @SaCheckRole("ADMIN")
    public Result<Integer> batchDeleteUsers(@RequestBody Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Result.fail("未指定要删除的用户");
        }

        try {
            int count = userService.batchDeleteUsers(ids);
            return Result.success(count, "成功删除" + count + "个用户");
        } catch (Exception e) {
            return Result.fail("批量删除用户失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有问题列表（管理员视图）
     */
    @Operation(summary = "获取所有问题列表", description = "分页获取所有问题，可按状态和关键字筛选，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "current", description = "当前页码", schema = @Schema(defaultValue = "1")),
        @Parameter(name = "size", description = "每页数量", schema = @Schema(defaultValue = "10")),
        @Parameter(name = "status", description = "问题状态：0-待审核，1-已发布，2-已解决，3-已关闭，4-被拒绝"),
        @Parameter(name = "keyword", description = "搜索关键词")
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/questions")
    @SaCheckRole("ADMIN")
    public Result<Page<QuestionVO>> getAllQuestions(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword) {

        Page<Question> page = new Page<>(current, size);

        try {
            Page<QuestionVO> questionVOPage = questionService.getQuestionPage(null, keyword, status, page);
            return Result.success(questionVOPage);
        } catch (Exception e) {
            return Result.fail("获取问题列表失败: " + e.getMessage());
        }
    }

    /**
     * 删除问题（管理员强制删除）
     */
    @Operation(summary = "删除问题", description = "管理员强制删除指定问题，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "删除成功")
    @DeleteMapping("/questions/{id}")
    @SaCheckRole("ADMIN")
    public Result<Void> deleteQuestion(@PathVariable Long id) {
        try {
            questionService.deleteQuestion(id);
            return Result.success();
        } catch (Exception e) {
            return Result.fail("删除问题失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除问题
     */
    @Operation(summary = "批量删除问题", description = "批量删除指定问题，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "操作成功")
    @DeleteMapping("/questions/batch")
    @SaCheckRole("ADMIN")
    public Result<Integer> batchDeleteQuestions(@RequestBody Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Result.fail("未指定要删除的问题");
        }

        try {
            int count = 0;
            for (Long id : ids) {
                questionService.deleteQuestion(id);
                count++;
            }
            return Result.success(count, "成功删除" + count + "个问题");
        } catch (Exception e) {
            return Result.fail("批量删除问题失败: " + e.getMessage());
        }
    }

    /**
     * 获取回答列表（管理员视图）
     */
    @Operation(summary = "获取回答列表", description = "分页获取所有回答，可按问题ID筛选，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "current", description = "当前页码", schema = @Schema(defaultValue = "1")),
        @Parameter(name = "size", description = "每页数量", schema = @Schema(defaultValue = "10")),
        @Parameter(name = "questionId", description = "问题ID，可选")
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/answers")
    @SaCheckRole("ADMIN")
    public Result<Page<AnswerVO>> getAnswers(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long questionId) {

        Page<Answer> page = new Page<>(current, size);

        try {
            // 使用新实现的getAllAnswers方法获取回答列表
            Page<AnswerVO> answerVOPage = answerService.getAllAnswers(questionId, page);
            return Result.success(answerVOPage);
        } catch (Exception e) {
            return Result.fail("获取回答列表失败: " + e.getMessage());
        }
    }

    /**
     * 删除回答（管理员强制删除）
     */
    @Operation(summary = "删除回答", description = "管理员强制删除指定回答，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "删除成功")
    @DeleteMapping("/answers/{id}")
    @SaCheckRole("ADMIN")
    public Result<Void> deleteAnswer(@PathVariable Long id) {
        try {
            answerService.deleteAnswer(id);
            return Result.success();
        } catch (Exception e) {
            return Result.fail("删除回答失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除回答
     */
    @Operation(summary = "批量删除回答", description = "批量删除指定回答，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "操作成功")
    @DeleteMapping("/answers/batch")
    @SaCheckRole("ADMIN")
    public Result<Integer> batchDeleteAnswers(@RequestBody Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Result.fail("未指定要删除的回答");
        }

        try {
            int count = 0;
            for (Long id : ids) {
                answerService.deleteAnswer(id);
                count++;
            }
            return Result.success(count, "成功删除" + count + "个回答");
        } catch (Exception e) {
            return Result.fail("批量删除回答失败: " + e.getMessage());
        }
    }


    /**
     * 删除评论（管理员强制删除）
     */
    @Operation(summary = "删除评论", description = "管理员强制删除指定评论，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "删除成功")
    @DeleteMapping("/comments/{id}")
    @SaCheckRole("ADMIN")
    public Result<Void> deleteComment(@PathVariable Long id) {
        try {
            commentService.deleteComment(id);
            return Result.success();
        } catch (Exception e) {
            return Result.fail("删除评论失败: " + e.getMessage());
        }
    }

    /**
     * 获取评论列表（管理员视图）
     */
    @Operation(summary = "获取评论列表", description = "分页获取所有评论，可按回答ID筛选，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
            @Parameter(name = "current", description = "当前页码", schema = @Schema(defaultValue = "1")),
            @Parameter(name = "size", description = "每页数量", schema = @Schema(defaultValue = "10")),
            @Parameter(name = "answerId", description = "回答ID，可选")
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/comments")
    @SaCheckRole("ADMIN")
    public Result<Page<CommentVO>> getComments(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long answerId) {

        Page<Comment> page = new Page<>(current, size);

        try {
            // 这里需要在CommentService中增加获取所有评论的方法
            Page<CommentVO> commentVOPage = commentService.getAllComments(answerId, page);
            return Result.success(commentVOPage);
        } catch (Exception e) {
            return Result.fail("获取评论列表失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除评论
     */
    @Operation(summary = "批量删除评论", description = "批量删除指定评论，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "操作成功")
    @DeleteMapping("/comments/batch")
    @SaCheckRole("ADMIN")
    public Result<Integer> batchDeleteComments(@RequestBody Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Result.fail("未指定要删除的评论");
        }

        try {
            int count = 0;
            for (Long id : ids) {
                commentService.deleteComment(id);
                count++;
            }
            return Result.success(count, "成功删除" + count + "个评论");
        } catch (Exception e) {
            return Result.fail("批量删除评论失败: " + e.getMessage());
        }
    }


    /**
     * 获取平台统计数据
     */
    @Operation(summary = "获取平台统计数据", description = "获取整个平台的统计数据，包括用户、问题、回答等，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/statistics/platform")
    @SaCheckRole("ADMIN")
    @Cacheable(value = "platformStatistics", key = "'all'", unless = "#result == null", cacheManager = "caffeineCacheManager")
    public Result<Map<String, Object>> getPlatformStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();

            // 使用CompletableFuture并行获取各类统计数据
            CompletableFuture<Map<String, Object>> userStatsFuture = CompletableFuture.supplyAsync(() -> userService.getUserStatistics());

            CompletableFuture<Long> totalQuestionsFuture = CompletableFuture.supplyAsync(() -> questionService.count());

            // 一次性查询所有问题状态并进行统计，避免多次数据库查询
            CompletableFuture<Map<Integer, Long>> questionStatusCountsFuture = CompletableFuture.supplyAsync(() -> {
                List<Question> allQuestions = questionService.list();
                return allQuestions.stream()
                    .collect(Collectors.groupingBy(Question::getStatus, Collectors.counting()));
            });

            CompletableFuture<Long> totalAnswersFuture = CompletableFuture.supplyAsync(() -> answerService.count());

            // 计算已采纳回答数
            CompletableFuture<Long> acceptedAnswersFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<Answer> acceptedWrapper = new LambdaQueryWrapper<>();
                acceptedWrapper.eq(Answer::getIsAccepted, 1);
                return answerService.count(acceptedWrapper);
            });

            // 获取热门问题
            CompletableFuture<List<Map<String, Object>>> hotQuestionsFuture = CompletableFuture.supplyAsync(() -> {
                Page<Question> hotQuestionsPage = new Page<>(1, 5);
                LambdaQueryWrapper<Question> hotQuestionsWrapper = new LambdaQueryWrapper<>();
                hotQuestionsWrapper.in(Question::getStatus, 1, 2);
                hotQuestionsWrapper.orderByDesc(Question::getViewCount);
                Page<Question> hotQuestions = questionService.page(hotQuestionsPage, hotQuestionsWrapper);

                List<Map<String, Object>> hotQuestionsData = new ArrayList<>();
                for (Question question : hotQuestions.getRecords()) {
                    Map<String, Object> questionData = new HashMap<>();
                    questionData.put("id", question.getId());
                    questionData.put("title", question.getTitle());
                    questionData.put("viewCount", question.getViewCount());
                    questionData.put("answerCount", question.getAnswerCount());
                    questionData.put("createTime", question.getCreateTime());
                    hotQuestionsData.add(questionData);
                }
                return hotQuestionsData;
            });

            // 获取活跃用户数据
            CompletableFuture<List<Map<String, Object>>> activeUsersFuture =
                CompletableFuture.supplyAsync(() -> userAnalyticsService.getActivityRanking(5));

            // 计算时间趋势统计
            CompletableFuture<Map<String, List<Object>>> trendDataFuture = CompletableFuture.supplyAsync(() -> {
                Map<String, List<Object>> trendData = new HashMap<>();
                List<String> dateLabels = new ArrayList<>();
                List<Integer> questionCounts = new ArrayList<>();
                List<Integer> answerCounts = new ArrayList<>();

                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM-dd");

                // 获取过去7天的所有问题和回答，然后在内存中分组计算
                LocalDateTime startTime = now.minusDays(6).withHour(0).withMinute(0).withSecond(0);

                // 一次性查询时间范围内的所有问题
                LambdaQueryWrapper<Question> questionsInRangeWrapper = new LambdaQueryWrapper<>();
                questionsInRangeWrapper.ge(Question::getCreateTime, startTime);
                List<Question> questionsInRange = questionService.list(questionsInRangeWrapper);

                // 一次性查询时间范围内的所有回答
                LambdaQueryWrapper<Answer> answersInRangeWrapper = new LambdaQueryWrapper<>();
                answersInRangeWrapper.ge(Answer::getCreateTime, startTime);
                List<Answer> answersInRange = answerService.list(answersInRangeWrapper);

                // 在内存中按日期分组计数
                Map<String, Integer> questionsByDate = new HashMap<>();
                Map<String, Integer> answersByDate = new HashMap<>();

                for (int i = 6; i >= 0; i--) {
                    LocalDateTime date = now.minusDays(i);
                    String dateLabel = date.format(dateFormatter);
                    dateLabels.add(dateLabel);

                    LocalDateTime dayStart = date.withHour(0).withMinute(0).withSecond(0);
                    LocalDateTime dayEnd = date.withHour(23).withMinute(59).withSecond(59);

                    // 初始化计数为0
                    questionsByDate.put(dateLabel, 0);
                    answersByDate.put(dateLabel, 0);
                }

                // 统计问题
                for (Question question : questionsInRange) {
                    LocalDateTime createTime = question.getCreateTime();
                    String dateLabel = createTime.format(dateFormatter);
                    if (questionsByDate.containsKey(dateLabel)) {
                        questionsByDate.put(dateLabel, questionsByDate.get(dateLabel) + 1);
                    }
                }

                // 统计回答
                for (Answer answer : answersInRange) {
                    LocalDateTime createTime = answer.getCreateTime();
                    String dateLabel = createTime.format(dateFormatter);
                    if (answersByDate.containsKey(dateLabel)) {
                        answersByDate.put(dateLabel, answersByDate.get(dateLabel) + 1);
                    }
                }

                // 按日期顺序填充结果
                for (String dateLabel : dateLabels) {
                    questionCounts.add(questionsByDate.get(dateLabel));
                    answerCounts.add(answersByDate.get(dateLabel));
                }

                trendData.put("dates", Collections.singletonList(dateLabels));
                trendData.put("questionCounts", Collections.singletonList(questionCounts));
                trendData.put("answerCounts", Collections.singletonList(answerCounts));
                return trendData;
            });

            // 等待所有异步任务完成并组合结果
            try {
                // 合并用户统计数据
                Map<String, Object> userStats = userStatsFuture.get();
                statistics.putAll(userStats);

                // 问题统计数据
                long totalQuestions = totalQuestionsFuture.get();
                statistics.put("totalQuestions", totalQuestions);

                Map<Integer, Long> questionStatusCounts = questionStatusCountsFuture.get();
                statistics.put("pendingQuestions", questionStatusCounts.getOrDefault(0, 0L));
                statistics.put("publishedQuestions", questionStatusCounts.getOrDefault(1, 0L));
                statistics.put("solvedQuestions", questionStatusCounts.getOrDefault(2, 0L));
                statistics.put("closedQuestions", questionStatusCounts.getOrDefault(3, 0L));
                statistics.put("rejectedQuestions", questionStatusCounts.getOrDefault(4, 0L));

                // 计算问题解决率
                long solvedQuestions = questionStatusCounts.getOrDefault(2, 0L);
                double solveRate = totalQuestions > 0
                    ? (double) solvedQuestions / totalQuestions * 100
                    : 0;
                statistics.put("questionSolveRate", Math.round(solveRate * 10) / 10.0);

                // 回答统计数据
                long totalAnswers = totalAnswersFuture.get();
                statistics.put("totalAnswers", totalAnswers);

                long acceptedAnswers = acceptedAnswersFuture.get();
                statistics.put("acceptedAnswers", acceptedAnswers);

                // 计算回答采纳率
                double acceptRate = totalAnswers > 0
                    ? (double) acceptedAnswers / totalAnswers * 100
                    : 0;
                statistics.put("answerAcceptRate", Math.round(acceptRate * 10) / 10.0);

                // 获取评论总数
                long totalComments = commentService.count();
                statistics.put("totalComments", totalComments);

                // 热门问题数据
                statistics.put("hotQuestions", hotQuestionsFuture.get());

                // 活跃用户数据
                statistics.put("activeUsers", activeUsersFuture.get());

                // 时间趋势数据
                statistics.put("trendData", trendDataFuture.get());

            } catch (InterruptedException | ExecutionException e) {
                log.error("获取平台统计数据异步任务执行失败", e);
                throw new RuntimeException("获取平台统计数据失败: " + e.getMessage());
            }

            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取平台统计数据失败", e);
            return Result.fail("获取平台统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取敏感内容统计
     */
    @Operation(summary = "获取敏感内容统计", description = "获取平台敏感内容统计数据，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/statistics/sensitive")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> getSensitiveContentStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();

            // 获取被拒绝的问题数量
            LambdaQueryWrapper<Question> rejectedWrapper = new LambdaQueryWrapper<>();
            rejectedWrapper.eq(Question::getStatus, 4);
            long rejectedQuestions = questionService.count(rejectedWrapper);
            statistics.put("rejectedQuestions", rejectedQuestions);

            // 获取被禁用的用户数量
            LambdaQueryWrapper<User> disabledWrapper = new LambdaQueryWrapper<>();
            disabledWrapper.eq(User::getStatus, 0);
            long disabledUsers = userService.count(disabledWrapper);
            statistics.put("disabledUsers", disabledUsers);

            return Result.success(statistics);
        } catch (Exception e) {
            return Result.fail("获取敏感内容统计失败: " + e.getMessage());
        }
    }


    /**
     * 敏感内容检测设置
     */
    @Operation(summary = "设置敏感词", description = "设置平台敏感词列表，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "设置成功")
    @PostMapping("/sensitive/words")
    @SaCheckRole("ADMIN")
    public Result<Void> setSensitiveWords(@RequestBody Map<String, List<String>> sensitiveWordsMap) {
        try {
            List<String> sensitiveWords = sensitiveWordsMap.get("words");
            if (sensitiveWords == null || sensitiveWords.isEmpty()) {
                return Result.fail("敏感词列表不能为空");
            }

            // 使用SensitiveContentService设置敏感词
            boolean success = sensitiveContentService.setSensitiveWords(sensitiveWords);
            if (success) {
                return Result.success();
            } else {
                return Result.fail("设置敏感词失败");
            }
        } catch (Exception e) {
            return Result.fail("设置敏感词失败: " + e.getMessage());
        }
    }

    /**
     * 获取敏感词列表
     */
    @Operation(summary = "获取敏感词", description = "获取平台当前敏感词列表，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/sensitive/words")
    @SaCheckRole("ADMIN")
    public Result<List<String>> getSensitiveWords() {
        try {
            // 使用SensitiveContentService获取敏感词
            List<String> sensitiveWords = sensitiveContentService.getSensitiveWords();
            return Result.success(sensitiveWords);
        } catch (Exception e) {
            return Result.fail("获取敏感词失败: " + e.getMessage());
        }
    }

    /**
     * 自动审核配置
     */
    @Operation(summary = "设置自动审核配置", description = "设置内容自动审核的规则和级别，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "设置成功")
    @PostMapping("/sensitive/auto-review")
    @SaCheckRole("ADMIN")
    public Result<Void> setAutoReviewConfig(@RequestBody Map<String, Object> config) {
        try {
            // 使用SensitiveContentService设置自动审核配置
            boolean success = sensitiveContentService.setAutoReviewConfig(config);
            if (success) {
                return Result.success();
            } else {
                return Result.fail("设置自动审核配置失败");
            }
        } catch (Exception e) {
            return Result.fail("设置自动审核配置失败: " + e.getMessage());
        }
    }

    /**
     * 获取自动审核配置
     */
    @Operation(summary = "获取自动审核配置", description = "获取当前内容自动审核的规则和级别，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/sensitive/auto-review")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> getAutoReviewConfig() {
        try {
            // 使用SensitiveContentService获取自动审核配置
            Map<String, Object> config = sensitiveContentService.getAutoReviewConfig();
            return Result.success(config);
        } catch (Exception e) {
            return Result.fail("获取自动审核配置失败: " + e.getMessage());
        }
    }

    /**
     * 敏感内容检测测试
     */
    @Operation(summary = "敏感内容检测测试", description = "测试文本是否包含敏感内容，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "检测成功")
    @PostMapping("/sensitive/detect")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> detectSensitiveContent(@RequestBody Map<String, String> params) {
        try {
            String text = params.get("text");
            if (text == null || text.isEmpty()) {
                return Result.fail("待检测文本不能为空");
            }

            // 使用SensitiveContentService检测敏感内容
            Map<String, Object> result = sensitiveContentService.detectSensitiveContent(text);

            // 添加自动审核结果
            result.put("autoReviewResult", sensitiveContentService.autoReviewContent(text));

            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("检测敏感内容失败: " + e.getMessage());
        }
    }

    /**
     * 用户行为分析 - 活跃度排行
     */
    @Operation(summary = "用户活跃度排行", description = "获取平台用户活跃度排行，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "limit", description = "返回数量", schema = @Schema(defaultValue = "10"))
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/analytics/users/active")
    @SaCheckRole("ADMIN")
    public Result<List<Map<String, Object>>> getUserActivityRanking(
            @RequestParam(defaultValue = "10") Integer limit) {
        try {
            // 使用UserAnalyticsService获取用户活跃度排行
            List<Map<String, Object>> ranking = userAnalyticsService.getActivityRanking(limit);
            return Result.success(ranking);
        } catch (Exception e) {
            return Result.fail("获取用户活跃度排行失败: " + e.getMessage());
        }
    }

    /**
     * 用户行为分析 - 异常行为检测
     */
    @Operation(summary = "异常行为检测", description = "检测平台用户的异常行为，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "days", description = "检测的天数", schema = @Schema(defaultValue = "7"))
    })
    @ApiResponse(responseCode = "200", description = "检测成功")
    @GetMapping("/analytics/users/abnormal")
    @SaCheckRole("ADMIN")
    public Result<List<Map<String, Object>>> detectAbnormalBehavior(
            @RequestParam(defaultValue = "7") Integer days) {
        try {
            // 使用UserAnalyticsService检测异常行为
            List<Map<String, Object>> abnormalUsers = userAnalyticsService.detectAbnormalBehavior(days);
            return Result.success(abnormalUsers);
        } catch (Exception e) {
            return Result.fail("检测异常行为失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户行为历史
     */
    @Operation(summary = "获取用户行为历史", description = "获取指定用户的行为历史，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "userId", description = "用户ID"),
        @Parameter(name = "days", description = "查询的天数", schema = @Schema(defaultValue = "7"))
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/analytics/users/{userId}/history")
    @SaCheckRole("ADMIN")
    public Result<List<Map<String, Object>>> getUserActionHistory(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "7") Integer days) {
        try {
            // 使用UserAnalyticsService获取用户行为历史
            List<Map<String, Object>> actionHistory = userAnalyticsService.getUserActionHistory(userId, days);
            return Result.success(actionHistory);
        } catch (Exception e) {
            return Result.fail("获取用户行为历史失败: " + e.getMessage());
        }
    }

    /**
     * 内容发布趋势分析
     */
    @Operation(summary = "内容发布趋势", description = "获取平台内容发布的时间趋势，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "days", description = "统计的天数", schema = @Schema(defaultValue = "30")),
        @Parameter(name = "type", description = "统计类型：question-问题，answer-回答，all-全部", schema = @Schema(defaultValue = "all"))
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/analytics/content/trend")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> getContentTrend(
            @RequestParam(defaultValue = "30") Integer days,
            @RequestParam(defaultValue = "all") String type) {
        try {
            // 这里需要添加内容趋势分析服务
            // Map<String, Object> trend = contentAnalyticsService.getContentTrend(days, type);

            // 临时返回一个示例趋势
            Map<String, Object> trend = new HashMap<>();
            List<String> dateList = new ArrayList<>();
            List<Integer> questionData = new ArrayList<>();
            List<Integer> answerData = new ArrayList<>();

            LocalDateTime now = LocalDateTime.now();
            for (int i = days - 1; i >= 0; i--) {
                LocalDateTime date = now.minusDays(i);
                dateList.add(date.format(DateTimeFormatter.ISO_LOCAL_DATE));

                // 模拟数据
                questionData.add(10 + (int)(Math.random() * 20));
                answerData.add(20 + (int)(Math.random() * 30));
            }

            trend.put("dates", dateList);
            trend.put("questionData", questionData);
            trend.put("answerData", answerData);

            return Result.success(trend);
        } catch (Exception e) {
            return Result.fail("获取内容发布趋势失败: " + e.getMessage());
        }
    }

    /**
     * 平台热门话题分析
     */
    @Operation(summary = "热门话题分析", description = "获取平台热门话题和标签统计，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "limit", description = "返回数量", schema = @Schema(defaultValue = "10"))
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/analytics/content/hot-topics")
    @SaCheckRole("ADMIN")
    @Cacheable(value = "hotTopics", key = "#limit", cacheManager = "caffeineCacheManager")
    public Result<List<Map<String, Object>>> getHotTopics(
            @RequestParam(defaultValue = "10") Integer limit) {
        try {
            // 获取所有已发布的问题
            long startTime = System.currentTimeMillis();
            log.info("开始获取热门话题分析");

            LambdaQueryWrapper<Question> questionWrapper = new LambdaQueryWrapper<>();
            questionWrapper.in(Question::getStatus, 1, 2, 3); // 已发布、已解决或已关闭的问题
            questionWrapper.eq(Question::getDeleted, 0);
            List<Question> questions = questionService.list(questionWrapper);

            log.info("查询问题耗时: {}ms, 问题数量: {}", System.currentTimeMillis() - startTime, questions.size());
            startTime = System.currentTimeMillis();

            // 优化：使用多线程并行处理大量数据
            Map<String, Map<String, Object>> topicStats = new HashMap<>();

            // 预处理：提取并汇总标签信息
            for (Question question : questions) {
                String tags = question.getTags();
                if (tags == null || tags.trim().isEmpty()) {
                    continue;
                }

                // 拆分标签
                String[] tagArray = tags.split(",");
                for (String tag : tagArray) {
                    tag = tag.trim();
                    if (tag.isEmpty()) {
                        continue;
                    }

                    // 初始化或更新标签统计
                    if (!topicStats.containsKey(tag)) {
                        Map<String, Object> stats = new HashMap<>();
                        stats.put("name", tag);
                        stats.put("questionCount", 0);
                        stats.put("answerCount", 0);
                        stats.put("viewCount", 0);
                        stats.put("hotScore", 0.0);
                        topicStats.put(tag, stats);
                    }

                    Map<String, Object> stats = topicStats.get(tag);
                    stats.put("questionCount", (int)stats.get("questionCount") + 1);
                    stats.put("viewCount", (int)stats.get("viewCount") + question.getViewCount());

                    // 累加到标签map中，避免重复查询数据库
                    stats.put("answerCount", (int)stats.get("answerCount"));
                }
            }

            log.info("处理标签统计耗时: {}ms", System.currentTimeMillis() - startTime);
            startTime = System.currentTimeMillis();

            // 批量查询回答数量，替代逐个问题查询
            if (!questions.isEmpty()) {
                List<Long> questionIds = questions.stream()
                    .map(Question::getId)
                    .collect(Collectors.toList());

                // 批量查询这些问题的回答
                LambdaQueryWrapper<Answer> answerWrapper = new LambdaQueryWrapper<>();
                answerWrapper.in(Answer::getQuestionId, questionIds);
                answerWrapper.eq(Answer::getDeleted, 0);
                List<Answer> answers = answerService.list(answerWrapper);

                log.info("批量查询回答耗时: {}ms, 回答数量: {}", System.currentTimeMillis() - startTime, answers.size());

                // 按问题ID分组统计回答
                Map<Long, List<Answer>> answersByQuestion = answers.stream()
                    .collect(Collectors.groupingBy(Answer::getQuestionId));

                // 为每个问题的标签增加回答数量
                for (Question question : questions) {
                    String tags = question.getTags();
                    if (tags == null || tags.trim().isEmpty()) {
                        continue;
                    }

                    int answerCount = answersByQuestion.getOrDefault(question.getId(), Collections.emptyList()).size();

                    // 更新该问题的所有标签的回答数
                    for (String tag : tags.split(",")) {
                        tag = tag.trim();
                        if (tag.isEmpty() || !topicStats.containsKey(tag)) {
                            continue;
                        }

                        Map<String, Object> stats = topicStats.get(tag);
                        stats.put("answerCount", (int)stats.get("answerCount") + answerCount);
                    }
                }
            }

            startTime = System.currentTimeMillis();

            // 计算热度分数
            for (Map<String, Object> stats : topicStats.values()) {
                // 计算热度分数：结合问题数、回答数和浏览量
                double hotScore =
                    (int)stats.get("questionCount") * 10 +
                    (int)stats.get("answerCount") * 5 +
                    (int)stats.get("viewCount") * 0.1;

                stats.put("hotScore", hotScore);
            }

            // 按热度排序
            List<Map<String, Object>> hotTopics = new ArrayList<>(topicStats.values());
            hotTopics.sort((a, b) -> Double.compare((double)b.get("hotScore"), (double)a.get("hotScore")));

            log.info("计算热度和排序耗时: {}ms", System.currentTimeMillis() - startTime);

            // 限制返回数量
            if (hotTopics.size() > limit) {
                hotTopics = hotTopics.subList(0, limit);
            }

            // 将热度分值四舍五入到整数
            for (Map<String, Object> topic : hotTopics) {
                topic.put("hotScore", Math.round((double)topic.get("hotScore")));
            }

            return Result.success(hotTopics);
        } catch (Exception e) {
            log.error("获取热门话题分析失败", e);
            return Result.fail("获取热门话题分析失败: " + e.getMessage());
        }
    }

    /**
     * 详细数据统计报表 - 用户分布
     */
    @Operation(summary = "用户分布统计", description = "获取平台用户分布统计数据，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/statistics/users/distribution")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> getUserDistributionStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();

            // 角色分布
            Map<String, Integer> roleDistribution = new HashMap<>();
            roleDistribution.put("普通用户", 0);
            roleDistribution.put("专家用户", 0);
            roleDistribution.put("管理员", 0);

            // 获取所有用户
            List<User> users = userService.list();

            // 统计角色分布
            for (User user : users) {
                switch (user.getRole()) {
                    case 1:
                        roleDistribution.put("普通用户", roleDistribution.get("普通用户") + 1);
                        break;
                    case 2:
                        roleDistribution.put("专家用户", roleDistribution.get("专家用户") + 1);
                        break;
                    case 3:
                        roleDistribution.put("管理员", roleDistribution.get("管理员") + 1);
                        break;
                }
            }

            statistics.put("roleDistribution", roleDistribution);

            // 注册时间分布（按月）
            Map<String, Integer> registerTimeDistribution = new HashMap<>();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

            for (User user : users) {
                if (user.getCreateTime() != null) {
                    String month = user.getCreateTime().format(formatter);
                    registerTimeDistribution.put(month, registerTimeDistribution.getOrDefault(month, 0) + 1);
                }
            }

            statistics.put("registerTimeDistribution", registerTimeDistribution);

            // 活跃度分布
            Map<String, Integer> activityDistribution = new HashMap<>();
            activityDistribution.put("高活跃", 0);
            activityDistribution.put("中活跃", 0);
            activityDistribution.put("低活跃", 0);
            activityDistribution.put("不活跃", 0);

            // 这里需要根据用户活跃度进行统计
            // 临时示例数据
            activityDistribution.put("高活跃", (int)(users.size() * 0.1));
            activityDistribution.put("中活跃", (int)(users.size() * 0.3));
            activityDistribution.put("低活跃", (int)(users.size() * 0.4));
            activityDistribution.put("不活跃", users.size() - activityDistribution.get("高活跃") - activityDistribution.get("中活跃") - activityDistribution.get("低活跃"));

            statistics.put("activityDistribution", activityDistribution);

            return Result.success(statistics);
        } catch (Exception e) {
            return Result.fail("获取用户分布统计失败: " + e.getMessage());
        }
    }

    /**
     * 详细数据统计报表 - 内容质量分析
     */
    @Operation(summary = "内容质量分析", description = "获取平台内容质量分析数据，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/statistics/content/quality")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> getContentQualityStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();

            // 问题质量分布
            Map<String, Integer> questionQuality = new HashMap<>();
            questionQuality.put("优质", 0);
            questionQuality.put("一般", 0);
            questionQuality.put("较差", 0);

            // 回答质量分布
            Map<String, Integer> answerQuality = new HashMap<>();
            answerQuality.put("优质", 0);
            answerQuality.put("一般", 0);
            answerQuality.put("较差", 0);

            // 获取所有已发布的问题（状态为1已发布、2已解决、3已关闭）
            LambdaQueryWrapper<Question> publishedQuestionWrapper = new LambdaQueryWrapper<>();
            publishedQuestionWrapper.in(Question::getStatus, 1, 2, 3);
            publishedQuestionWrapper.eq(Question::getDeleted, 0);
            List<Question> questions = questionService.list(publishedQuestionWrapper);

            // 获取所有回答
            LambdaQueryWrapper<Answer> answerWrapper = new LambdaQueryWrapper<>();
            answerWrapper.eq(Answer::getDeleted, 0);
            List<Answer> answers = answerService.list(answerWrapper);

            // 根据浏览量和回答数判断问题质量
            for (Question question : questions) {
                if (question.getViewCount() >= 100 || question.getAnswerCount() >= 5) {
                    questionQuality.put("优质", questionQuality.get("优质") + 1);
                } else if (question.getViewCount() >= 50 || question.getAnswerCount() >= 2) {
                    questionQuality.put("一般", questionQuality.get("一般") + 1);
                } else {
                    questionQuality.put("较差", questionQuality.get("较差") + 1);
                }
            }

            // 根据点赞数和是否采纳判断回答质量
            for (Answer answer : answers) {
                if (answer.getIsAccepted() == 1 || answer.getVoteCount() >= 10) {
                    answerQuality.put("优质", answerQuality.get("优质") + 1);
                } else if (answer.getVoteCount() >= 3) {
                    answerQuality.put("一般", answerQuality.get("一般") + 1);
                } else {
                    answerQuality.put("较差", answerQuality.get("较差") + 1);
                }
            }

            statistics.put("questionQuality", questionQuality);
            statistics.put("answerQuality", answerQuality);

            // 内容审核统计
            Map<String, Integer> reviewStatistics = new HashMap<>();

            // 查询所有问题（包括已删除的）
            List<Question> allQuestions = questionService.list();

            int pendingCount = 0;
            int approvedCount = 0;
            int rejectedCount = 0;

            for (Question question : allQuestions) {
                if (question.getStatus() == 0) {
                    pendingCount++;
                } else if (question.getStatus() == 4) {
                    rejectedCount++;
                } else if (question.getStatus() >= 1 && question.getStatus() <= 3) {
                    approvedCount++;
                }
            }

            reviewStatistics.put("待审核", pendingCount);
            reviewStatistics.put("已通过", approvedCount);
            reviewStatistics.put("已拒绝", rejectedCount);

            statistics.put("reviewStatistics", reviewStatistics);

            // 添加近期内容质量趋势
            Map<String, Object> qualityTrend = getQualityTrendData();
            statistics.put("qualityTrend", qualityTrend);

            // 添加敏感内容检测统计
            Map<String, Object> sensitiveContentStats = getSensitiveContentStats();
            statistics.put("sensitiveContentStats", sensitiveContentStats);

            return Result.success(statistics);
        } catch (Exception e) {
            return Result.fail("获取内容质量分析失败: " + e.getMessage());
        }
    }

    /**
     * 获取内容质量趋势数据
     * @return 质量趋势数据
     */
    private Map<String, Object> getQualityTrendData() {
        Map<String, Object> trendData = new HashMap<>();
        List<String> dateLabels = new ArrayList<>();
        List<Integer> highQualityQuestions = new ArrayList<>();
        List<Integer> highQualityAnswers = new ArrayList<>();

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM-dd");

        // 最近7天的数据
        for (int i = 6; i >= 0; i--) {
            LocalDateTime date = now.minusDays(i);
            String dateLabel = date.format(dateFormatter);
            dateLabels.add(dateLabel);

            LocalDateTime startTime = date.withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime endTime = date.withHour(23).withMinute(59).withSecond(59).withNano(999999999);

            // 当日高质量问题数（浏览量>=50或回答数>=3）
            LambdaQueryWrapper<Question> highQualityQuestionWrapper = new LambdaQueryWrapper<>();
            highQualityQuestionWrapper.between(Question::getCreateTime, startTime, endTime);
            highQualityQuestionWrapper.and(q ->
                q.ge(Question::getViewCount, 50).or().ge(Question::getAnswerCount, 3)
            );
            int dayHighQualityQuestionCount = Math.toIntExact(questionService.count(highQualityQuestionWrapper));
            highQualityQuestions.add(dayHighQualityQuestionCount);

            // 当日高质量回答数（被采纳或点赞数>=5）
            LambdaQueryWrapper<Answer> highQualityAnswerWrapper = new LambdaQueryWrapper<>();
            highQualityAnswerWrapper.between(Answer::getCreateTime, startTime, endTime);
            highQualityAnswerWrapper.and(a ->
                a.eq(Answer::getIsAccepted, 1).or().ge(Answer::getVoteCount, 5)
            );
            int dayHighQualityAnswerCount = Math.toIntExact(answerService.count(highQualityAnswerWrapper));
            highQualityAnswers.add(dayHighQualityAnswerCount);
        }

        trendData.put("dates", dateLabels);
        trendData.put("highQualityQuestions", highQualityQuestions);
        trendData.put("highQualityAnswers", highQualityAnswers);

        return trendData;
    }

    /**
     * 获取敏感内容统计数据
     * @return 敏感内容统计
     */
    private Map<String, Object> getSensitiveContentStats() {
        Map<String, Object> statistics = new HashMap<>();

        try {
            // 获取被拒绝的问题数量
            LambdaQueryWrapper<Question> rejectedWrapper = new LambdaQueryWrapper<>();
            rejectedWrapper.eq(Question::getStatus, 4);
            long rejectedQuestions = questionService.count(rejectedWrapper);
            statistics.put("rejectedQuestions", rejectedQuestions);

            // 获取被禁用的用户数量
            LambdaQueryWrapper<User> disabledWrapper = new LambdaQueryWrapper<>();
            disabledWrapper.eq(User::getStatus, 0);
            long disabledUsers = userService.count(disabledWrapper);
            statistics.put("disabledUsers", disabledUsers);

            // 获取敏感词列表
            List<String> sensitiveWords = sensitiveContentService.getSensitiveWords();
            statistics.put("sensitiveWordCount", sensitiveWords.size());

            // 获取敏感词TOP5（假设sensitiveContentService提供了这个方法）
            // statistics.put("topSensitiveWords", sensitiveContentService.getTopSensitiveWords(5));

            // 自动审核配置
            Map<String, Object> autoReviewConfig = sensitiveContentService.getAutoReviewConfig();
            statistics.put("autoReviewConfig", autoReviewConfig);

        } catch (Exception e) {
            // 记录异常但继续返回已收集的数据
            log.error("获取敏感内容统计失败", e);
        }

        return statistics;
    }

    /**
     * 平台运营分析
     */
    @Operation(summary = "平台运营分析", description = "获取平台运营效果分析数据，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/statistics/platform/operation")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> getPlatformOperationStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();

            // 平台增长指标
            Map<String, Object> growthMetrics = new HashMap<>();
            growthMetrics.put("dailyNewUsers", 15);
            growthMetrics.put("weeklyNewUsers", 87);
            growthMetrics.put("monthlyNewUsers", 342);
            growthMetrics.put("dailyNewQuestions", 28);
            growthMetrics.put("weeklyNewQuestions", 189);
            growthMetrics.put("monthlyNewQuestions", 723);

            statistics.put("growthMetrics", growthMetrics);

            // 用户留存率
            Map<String, Object> retentionRate = new HashMap<>();
            retentionRate.put("oneDay", 78.5);
            retentionRate.put("sevenDays", 52.3);
            retentionRate.put("thirtyDays", 31.7);

            statistics.put("retentionRate", retentionRate);

            // 平台活跃指标
            Map<String, Object> activityMetrics = new HashMap<>();
            activityMetrics.put("dailyActiveUsers", 126);
            activityMetrics.put("weeklyActiveUsers", 487);
            activityMetrics.put("monthlyActiveUsers", 1243);
            activityMetrics.put("avgDailyQuestionViews", 1872);
            activityMetrics.put("avgDailyAnswers", 93);

            statistics.put("activityMetrics", activityMetrics);

            // 问题解决率
            long totalQuestions = questionService.count();
            LambdaQueryWrapper<Question> solvedWrapper = new LambdaQueryWrapper<>();
            solvedWrapper.eq(Question::getStatus, 2);
            long solvedQuestions = questionService.count(solvedWrapper);

            double solveRate = totalQuestions > 0 ? (double) solvedQuestions / totalQuestions * 100 : 0;
            statistics.put("questionSolveRate", Math.round(solveRate * 10) / 10.0);

            // 平均回答时间（小时）
            statistics.put("avgAnswerTime", 6.3);

            return Result.success(statistics);
        } catch (Exception e) {
            return Result.fail("获取平台运营分析失败: " + e.getMessage());
        }
    }

    /**
     * 获取仪表盘数据
     */
    @Operation(summary = "获取仪表盘数据", description = "获取管理后台仪表盘所需的综合数据，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/dashboard")
    @SaCheckRole("ADMIN")
    @Cacheable(value = "dashboardData", key = "'all'", unless = "#result == null", cacheManager = "caffeineCacheManager")
    public Result<Map<String, Object>> getDashboardData() {
        try {
            Map<String, Object> dashboardData = new HashMap<>();
            LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime yesterday = today.minusDays(1);

            // 使用CompletableFuture并行执行查询，提高响应速度
            CompletableFuture<Long> userCountFuture = CompletableFuture.supplyAsync(userService::count,dashboardTaskExecutor);

            CompletableFuture<Long> todayNewUsersFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<User> todayUserWrapper = new LambdaQueryWrapper<>();
                todayUserWrapper.ge(User::getCreateTime, today);
                return userService.count(todayUserWrapper);
            },dashboardTaskExecutor);

            CompletableFuture<Long> questionCountFuture = CompletableFuture.supplyAsync(questionService::count,dashboardTaskExecutor);

            CompletableFuture<Long> pendingQuestionsFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<Question> pendingWrapper = new LambdaQueryWrapper<>();
                pendingWrapper.eq(Question::getStatus, 0);
                return questionService.count(pendingWrapper);
            },dashboardTaskExecutor);

            CompletableFuture<Long> answerCountFuture = CompletableFuture.supplyAsync(answerService::count,dashboardTaskExecutor);

            CompletableFuture<Long> todayNewAnswersFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<Answer> todayAnswerWrapper = new LambdaQueryWrapper<>();
                todayAnswerWrapper.ge(Answer::getCreateTime, today);
                return answerService.count(todayAnswerWrapper);
            },dashboardTaskExecutor);

            CompletableFuture<Long> acceptedCountFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<Answer> acceptedWrapper = new LambdaQueryWrapper<>();
                acceptedWrapper.eq(Answer::getIsAccepted, 1);
                return answerService.count(acceptedWrapper);
            },dashboardTaskExecutor);

            CompletableFuture<Long> commentCountFuture = CompletableFuture.supplyAsync(commentService::count,dashboardTaskExecutor);

            CompletableFuture<List<Map<String, Object>>> activeUsersFuture =
                CompletableFuture.supplyAsync(() -> userAnalyticsService.getActivityRanking(5),dashboardTaskExecutor);

            CompletableFuture<Long> todayNewQuestionsFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<Question> todayQuestionWrapper = new LambdaQueryWrapper<>();
                todayQuestionWrapper.ge(Question::getCreateTime, today);
                return questionService.count(todayQuestionWrapper);
            },dashboardTaskExecutor);

            CompletableFuture<Long> yesterdayNewQuestionsFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<Question> yesterdayQuestionWrapper = new LambdaQueryWrapper<>();
                yesterdayQuestionWrapper.ge(Question::getCreateTime, yesterday);
                yesterdayQuestionWrapper.lt(Question::getCreateTime, today);
                return questionService.count(yesterdayQuestionWrapper);
            },dashboardTaskExecutor);

            // 获取待审核问题列表
            CompletableFuture<List<Map<String, Object>>> recentPendingQuestionsFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<Question> pendingWrapper = new LambdaQueryWrapper<>();
                pendingWrapper.eq(Question::getStatus, 0);
                pendingWrapper.orderByDesc(Question::getCreateTime);
                Page<Question> pendingPage = new Page<>(1, 5);
                Page<Question> pendingResult = questionService.page(pendingPage, pendingWrapper);

                List<Map<String, Object>> recentPendingQuestions = new ArrayList<>();

                // 获取所有相关用户的ID
                Set<Long> userIds = pendingResult.getRecords().stream()
                    .map(Question::getUserId)
                    .collect(Collectors.toSet());

                // 批量查询用户信息
                Map<Long, User> userMap = new HashMap<>();
                if (!userIds.isEmpty()) {
                    LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
                    userWrapper.in(User::getId, userIds);
                    List<User> users = userService.list(userWrapper);
                    for (User user : users) {
                        userMap.put(user.getId(), user);
                    }
                }

                for (Question question : pendingResult.getRecords()) {
                    Map<String, Object> questionMap = new HashMap<>();
                    questionMap.put("id", question.getId());
                    questionMap.put("title", question.getTitle());
                    questionMap.put("userId", question.getUserId());

                    // 使用之前查询的用户信息
                    User user = userMap.get(question.getUserId());
                    if (user != null) {
                        questionMap.put("userName", user.getUsername());
                        questionMap.put("userNickname", user.getNickname());
                    }

                    questionMap.put("createTime", question.getCreateTime());
                    recentPendingQuestions.add(questionMap);
                }
                return recentPendingQuestions;
            },dashboardTaskExecutor);

            // 系统活动通知
            CompletableFuture<List<Map<String, Object>>> recentActivitiesFuture =
                CompletableFuture.supplyAsync(this::getRecentSystemActivities,dashboardTaskExecutor);

            // 热门问题
            CompletableFuture<List<Map<String, Object>>> hotQuestionsFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<Question> hotQuestionWrapper = new LambdaQueryWrapper<>();
                hotQuestionWrapper.in(Question::getStatus, 1, 2, 3); // 已发布、已解决或已关闭的问题
                hotQuestionWrapper.orderByDesc(Question::getViewCount);
                Page<Question> hotQuestionPage = new Page<>(1, 5);
                Page<Question> hotQuestionResult = questionService.page(hotQuestionPage, hotQuestionWrapper);

                List<Map<String, Object>> hotQuestions = new ArrayList<>();
                for (Question question : hotQuestionResult.getRecords()) {
                    Map<String, Object> questionMap = new HashMap<>();
                    questionMap.put("id", question.getId());
                    questionMap.put("title", question.getTitle());
                    questionMap.put("viewCount", question.getViewCount());
                    questionMap.put("answerCount", question.getAnswerCount());
                    hotQuestions.add(questionMap);
                }
                return hotQuestions;
            },dashboardTaskExecutor);

            // 等待所有异步任务完成并组合结果
            try {
                dashboardData.put("userCount", userCountFuture.get());
                dashboardData.put("todayNewUsers", todayNewUsersFuture.get());
                dashboardData.put("questionCount", questionCountFuture.get());
                dashboardData.put("pendingQuestions", pendingQuestionsFuture.get());
                dashboardData.put("answerCount", answerCountFuture.get());
                dashboardData.put("todayNewAnswers", todayNewAnswersFuture.get());

                Long answerCount = answerCountFuture.get();
                Long acceptedCount = acceptedCountFuture.get();
                String acceptRate = answerCount > 0
                    ? String.format("%.1f%%", (acceptedCount * 100.0 / answerCount))
                    : "0%";
                dashboardData.put("acceptRate", acceptRate);

                dashboardData.put("commentCount", commentCountFuture.get());
                dashboardData.put("activeUsers", activeUsersFuture.get());
                dashboardData.put("todayNewQuestions", todayNewQuestionsFuture.get());

                Long todayNewQuestions = todayNewQuestionsFuture.get();
                Long yesterdayNewQuestions = yesterdayNewQuestionsFuture.get();

                // 计算问题环比增长率
                int questionGrowthRate = 0;
                if (yesterdayNewQuestions > 0) {
                    questionGrowthRate = (int)(((double)todayNewQuestions - yesterdayNewQuestions) / yesterdayNewQuestions * 100);
                } else if (todayNewQuestions > 0) {
                    questionGrowthRate = 100; // 昨天为0，今天有新增，增长100%
                }
                dashboardData.put("questionGrowthRate", questionGrowthRate);

                dashboardData.put("recentPendingQuestions", recentPendingQuestionsFuture.get());
                dashboardData.put("recentActivities", recentActivitiesFuture.get());
                dashboardData.put("hotQuestions", hotQuestionsFuture.get());

            } catch (InterruptedException | ExecutionException e) {
                log.error("获取仪表盘数据异步任务执行失败", e);
                throw new RuntimeException("获取仪表盘数据失败: " + e.getMessage());
            }

            return Result.success(dashboardData);
        } catch (Exception e) {
            log.error("获取仪表盘数据失败", e);
            return Result.fail("获取仪表盘数据失败: " + e.getMessage());
        }
    }

    /**
     * 优化后的获取系统最近活动记录方法
     * @return 系统活动列表
     */
    private List<Map<String, Object>> getRecentSystemActivities() {
        List<Map<String, Object>> activities = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        try {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime oneWeekAgo = now.minusWeeks(1);

            // 一次性查询最近审核的问题和新注册用户
            CompletableFuture<List<Question>> recentReviewsFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<Question> recentReviewWrapper = new LambdaQueryWrapper<>();
                recentReviewWrapper.in(Question::getStatus, 1, 4); // 已通过或已拒绝
                recentReviewWrapper.ge(Question::getUpdateTime, oneWeekAgo);
                recentReviewWrapper.orderByDesc(Question::getUpdateTime);
                Page<Question> recentReviewPage = new Page<>(1, 3);
                return questionService.page(recentReviewPage, recentReviewWrapper).getRecords();
            });

            CompletableFuture<List<User>> recentUsersFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<User> recentUserWrapper = new LambdaQueryWrapper<>();
                recentUserWrapper.ge(User::getCreateTime, oneWeekAgo);
                recentUserWrapper.orderByDesc(User::getCreateTime);
                Page<User> recentUserPage = new Page<>(1, 2);
                return userService.page(recentUserPage, recentUserWrapper).getRecords();
            });

            // 处理问题审核记录
            for (Question question : recentReviewsFuture.get()) {
                Map<String, Object> activity = new HashMap<>();
                if (question.getStatus() == 1) {
                    activity.put("content", "问题《" + question.getTitle() + "》审核通过");
                    activity.put("type", "success");
                } else {
                    activity.put("content", "问题《" + question.getTitle() + "》审核拒绝");
                    activity.put("type", "warning");
                }
                activity.put("time", question.getUpdateTime().format(formatter));
                activities.add(activity);
            }

            // 处理新用户记录
            for (User user : recentUsersFuture.get()) {
                Map<String, Object> activity = new HashMap<>();
                activity.put("content", "新用户 " + user.getNickname() + " 注册成功");
                activity.put("type", "info");
                activity.put("time", user.getCreateTime().format(formatter));
                activities.add(activity);
            }

            // 排序活动，按时间倒序
            activities.sort((a, b) -> {
                String timeA = (String) a.get("time");
                String timeB = (String) b.get("time");
                return timeB.compareTo(timeA);
            });

            // 限制返回数量
            if (activities.size() > 5) {
                activities = activities.subList(0, 5);
            }

        } catch (Exception e) {
            log.error("获取系统活动记录失败", e);

            // 出错时返回默认数据
            Map<String, Object> defaultActivity = new HashMap<>();
            defaultActivity.put("content", "系统正常运行中");
            defaultActivity.put("type", "info");
            defaultActivity.put("time", LocalDateTime.now().format(formatter));
            activities.add(defaultActivity);
        }

        return activities;
    }

    /**
     * 获取敏感内容历史记录
     */
    @Operation(summary = "获取敏感内容历史记录", description = "获取系统检测到的敏感内容历史记录，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "current", description = "当前页码", schema = @Schema(defaultValue = "1")),
        @Parameter(name = "size", description = "每页数量", schema = @Schema(defaultValue = "10")),
        @Parameter(name = "type", description = "内容类型：question-问题，answer-回答，comment-评论", schema = @Schema(defaultValue = "all")),
        @Parameter(name = "days", description = "查询的天数", schema = @Schema(defaultValue = "30"))
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/sensitive/history")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> getSensitiveContentHistory(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "all") String type,
            @RequestParam(defaultValue = "30") Integer days) {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> historyRecords = new ArrayList<>();

            // 计算查询时间范围
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusDays(days);

            if ("question".equals(type) || "all".equals(type)) {
                // 获取被拒绝的敏感问题
                LambdaQueryWrapper<Question> sensitiveQuestionWrapper = new LambdaQueryWrapper<>();
                sensitiveQuestionWrapper.eq(Question::getStatus, 4); // 被拒绝的
                sensitiveQuestionWrapper.between(Question::getUpdateTime, startTime, endTime);
                sensitiveQuestionWrapper.orderByDesc(Question::getUpdateTime);

                // 如果是all类型，只取前5条记录
                List<Question> sensitiveQuestions;
                if ("all".equals(type)) {
                    Page<Question> questionPage = new Page<>(1, 5);
                    sensitiveQuestions = questionService.page(questionPage, sensitiveQuestionWrapper).getRecords();
                } else {
                    Page<Question> questionPage = new Page<>(current, size);
                    Page<Question> questionsPage = questionService.page(questionPage, sensitiveQuestionWrapper);
                    sensitiveQuestions = questionsPage.getRecords();

                    // 添加分页信息
                    result.put("total", questionsPage.getTotal());
                    result.put("pages", questionsPage.getPages());
                    result.put("current", questionsPage.getCurrent());
                    result.put("size", questionsPage.getSize());
                }

                for (Question question : sensitiveQuestions) {
                    Map<String, Object> record = new HashMap<>();
                    record.put("id", question.getId());
                    record.put("type", "问题");
                    record.put("title", question.getTitle());
                    record.put("content", question.getContent());
                    record.put("reason", question.getRemark()); // 拒绝原因
                    record.put("createTime", question.getCreateTime());
                    record.put("rejectTime", question.getUpdateTime());

                    // 获取用户信息
                    User user = userService.getById(question.getUserId());
                    if (user != null) {
                        record.put("userId", user.getId());
                        record.put("username", user.getUsername());
                        record.put("nickname", user.getNickname());
                    }

                    historyRecords.add(record);
                }
            }

            // 如果需要排序，可以在这里进行
            historyRecords.sort((a, b) -> ((LocalDateTime)b.get("rejectTime")).compareTo((LocalDateTime)a.get("rejectTime")));

            result.put("records", historyRecords);

            // 统计数据
            Map<String, Object> stats = new HashMap<>();

            // 获取不同时间段的敏感内容数量
            LambdaQueryWrapper<Question> last7DaysWrapper = new LambdaQueryWrapper<>();
            last7DaysWrapper.eq(Question::getStatus, 4);
            last7DaysWrapper.between(Question::getUpdateTime, endTime.minusDays(7), endTime);
            long last7DaysCount = questionService.count(last7DaysWrapper);
            stats.put("last7DaysCount", last7DaysCount);

            LambdaQueryWrapper<Question> last30DaysWrapper = new LambdaQueryWrapper<>();
            last30DaysWrapper.eq(Question::getStatus, 4);
            last30DaysWrapper.between(Question::getUpdateTime, endTime.minusDays(30), endTime);
            long last30DaysCount = questionService.count(last30DaysWrapper);
            stats.put("last30DaysCount", last30DaysCount);

            // 敏感内容类型分布
            stats.put("questionCount", questionService.count(new LambdaQueryWrapper<Question>().eq(Question::getStatus, 4)));

            // 添加统计数据
            result.put("stats", stats);

            return Result.success(result);
        } catch (Exception e) {
            log.error("获取敏感内容历史记录失败", e);
            return Result.fail("获取敏感内容历史记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取敏感词排行
     */
    @Operation(summary = "获取敏感词排行", description = "获取系统中出现频率最高的敏感词，需要管理员权限")
    @SecurityRequirement(name = "Authorization")
    @Parameters({
        @Parameter(name = "limit", description = "返回数量", schema = @Schema(defaultValue = "10"))
    })
    @ApiResponse(responseCode = "200", description = "获取成功")
    @GetMapping("/sensitive/ranking")
    @SaCheckRole("ADMIN")
    public Result<List<Map<String, Object>>> getSensitiveWordRanking(
            @RequestParam(defaultValue = "10") Integer limit) {
        try {
            // 获取敏感词列表
            List<String> sensitiveWords = sensitiveContentService.getSensitiveWords();
            if (sensitiveWords.isEmpty()) {
                return Result.success(new ArrayList<>());
            }

            // 统计各敏感词出现次数
            Map<String, Integer> wordFrequency = new HashMap<>();
            for (String word : sensitiveWords) {
                wordFrequency.put(word, 0);
            }

            // 获取所有被拒绝的问题
            LambdaQueryWrapper<Question> rejectedQuestionWrapper = new LambdaQueryWrapper<>();
            rejectedQuestionWrapper.eq(Question::getStatus, 4); // 被拒绝的
            List<Question> rejectedQuestions = questionService.list(rejectedQuestionWrapper);

            // 分析问题内容中敏感词出现频率
            for (Question question : rejectedQuestions) {
                String content = question.getTitle() + " " + question.getContent();
                for (String word : sensitiveWords) {
                    int count = countOccurrences(content, word);
                    if (count > 0) {
                        wordFrequency.put(word, wordFrequency.get(word) + count);
                    }
                }
            }

            // 将结果转为列表并排序
            List<Map<String, Object>> ranking = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : wordFrequency.entrySet()) {
                if (entry.getValue() > 0) {
                    Map<String, Object> item = new HashMap<>();
                    item.put("word", entry.getKey());
                    item.put("count", entry.getValue());
                    ranking.add(item);
                }
            }

            // 按出现次数排序
            ranking.sort((a, b) -> Integer.compare((int)b.get("count"), (int)a.get("count")));

            // 限制返回数量
            if (ranking.size() > limit) {
                ranking = ranking.subList(0, limit);
            }

            return Result.success(ranking);
        } catch (Exception e) {
            log.error("获取敏感词排行失败", e);
            return Result.fail("获取敏感词排行失败: " + e.getMessage());
        }
    }

    /**
     * 统计字符串中子串出现的次数
     * @param text 文本
     * @param subString 子串
     * @return 出现次数
     */
    private int countOccurrences(String text, String subString) {
        if (text == null || text.isEmpty() || subString == null || subString.isEmpty()) {
            return 0;
        }

        int count = 0;
        int index = 0;
        while ((index = text.indexOf(subString, index)) != -1) {
            count++;
            index += subString.length();
        }
        return count;
    }

    /**
     * 问题自动审核
     */
    @Operation(summary = "问题自动审核", description = "对即将提交的问题内容进行自动审核检测，返回审核建议")
    @SecurityRequirement(name = "Authorization")
    @ApiResponse(responseCode = "200", description = "审核成功")
    @PostMapping("/questions/auto-review")
    @SaCheckRole("ADMIN")
    public Result<Map<String, Object>> autoReviewQuestion(@RequestBody Map<String, String> params) {
        try {
            String title = params.get("title");
            String content = params.get("content");
            String tags = params.get("tags");

            if (title == null || title.isEmpty()) {
                return Result.fail("问题标题不能为空");
            }

            Map<String, Object> result = new HashMap<>();

            // 1. 敏感内容检测 - 标题
            Map<String, Object> titleResult = sensitiveContentService.detectSensitiveContent(title);
            boolean titlePassed = (boolean) titleResult.get("passed");
            List<String> titleSensitiveWords = (List<String>) titleResult.get("sensitiveWords");

            // 2. 敏感内容检测 - 内容
            Map<String, Object> contentResult = sensitiveContentService.detectSensitiveContent(content);
            boolean contentPassed = (boolean) contentResult.get("passed");
            List<String> contentSensitiveWords = (List<String>) contentResult.get("sensitiveWords");

            // 3. 敏感内容检测 - 标签
            Map<String, Object> tagsResult = sensitiveContentService.detectSensitiveContent(tags);
            boolean tagsPassed = (boolean) tagsResult.get("passed");
            List<String> tagsSensitiveWords = (List<String>) tagsResult.get("sensitiveWords");

            // 合并所有敏感词
            Set<String> allSensitiveWords = new HashSet<>();
            allSensitiveWords.addAll(titleSensitiveWords);
            allSensitiveWords.addAll(contentSensitiveWords);
            allSensitiveWords.addAll(tagsSensitiveWords);

            // 获取自动审核配置
            Map<String, Object> config = sensitiveContentService.getAutoReviewConfig();
            boolean autoRejectEnabled = Boolean.parseBoolean(config.getOrDefault("autoRejectEnabled", false).toString());
            String sensitivityLevel = config.getOrDefault("sensitivityLevel", "medium").toString();

            // 综合判断审核结果
            String reviewResult;
            String reviewSuggestion;
            int riskLevel;

            if (allSensitiveWords.isEmpty()) {
                // 无敏感词，直接通过
                reviewResult = "通过";
                reviewSuggestion = "内容无违规，可直接通过";
                riskLevel = 0;
            } else {
                // 有敏感词，根据数量和配置判断
                int sensitiveWordCount = allSensitiveWords.size();

                // 根据敏感级别设置阈值
                int rejectThreshold;
                switch (sensitivityLevel) {
                    case "low":
                        rejectThreshold = 5;
                        break;
                    case "high":
                        rejectThreshold = 1;
                        break;
                    default: // medium
                        rejectThreshold = 3;
                        break;
                }

                if (sensitiveWordCount >= rejectThreshold && autoRejectEnabled) {
                    // 超过阈值，且启用了自动拒绝
                    reviewResult = "拒绝";
                    reviewSuggestion = "内容包含较多敏感词，建议拒绝";
                    riskLevel = 3;
                } else if (sensitiveWordCount >= rejectThreshold) {
                    // 超过阈值，但未启用自动拒绝
                    reviewResult = "人工审核";
                    reviewSuggestion = "内容包含较多敏感词，建议人工审核";
                    riskLevel = 2;
                } else {
                    // 未超过阈值
                    reviewResult = "人工审核";
                    reviewSuggestion = "内容包含少量敏感词，建议人工审核";
                    riskLevel = 1;
                }
            }

            // 构建返回结果
            result.put("reviewResult", reviewResult);
            result.put("reviewSuggestion", reviewSuggestion);
            result.put("riskLevel", riskLevel);
            result.put("sensitiveWords", new ArrayList<>(allSensitiveWords));
            result.put("titleResult", titleResult);
            result.put("contentResult", contentResult);
            result.put("tagsResult", tagsResult);

            return Result.success(result);
        } catch (Exception e) {
            log.error("问题自动审核失败", e);
            return Result.fail("问题自动审核失败: " + e.getMessage());
        }
    }

    /**
     * 发送系统通知
     */
    @Operation(summary = "发送系统通知", description = "管理员发送系统通知")
    @PostMapping("/notification/send")
    @SaCheckRole("admin")
    public Result<Void> sendSystemNotification(@RequestBody @Validated SystemNotificationDTO notificationDTO) {
        notificationProducer.sendSystemNotification(
                notificationDTO.getTitle(),
                notificationDTO.getContent(),
                notificationDTO.getReceiverId()
        );
        return Result.success();
    }
}
